<template>
  <el-card class="mt-10">
    <el-form
      label-width="100px"
      ref="spuFormRef"
      :model="spuFormData"
      :rules="spuFormRules"
    >
      <el-form-item label="SPU名称" prop="spuName">
        <el-input placeholder="SPU名称" v-model="spuFormData.spuName" />
      </el-form-item>
      <el-form-item label="品牌" prop="tmId">
        <el-select placeholder="请选择" v-model="spuFormData.tmId">
          <el-option
            v-for="allTrademark in allTrademarkList"
            :key="allTrademark.id"
            :label="allTrademark.tmName"
            :value="allTrademark.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述" prop="description">
        <el-input type="textarea" v-model="spuFormData.description" />
      </el-form-item>
      <el-form-item label="SPU图片" prop="spuImageList">
        <!-- file-list="xxx" 上传图片成功   自动添加数据进入 
         :on-preview  点击预览图片触发的回调
        -->
        <el-upload
          class="spu-upload"
          v-model:file-list="spuFormData.spuImageList"
          :action="`${BASE_URL}/admin/product/fileUpload`"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :before-upload="beforeAvatarUpload"
          :on-success="handleAvatarSuccess"
          :limit="MAX_UPLOAD_NUM"
        >
          <el-icon><Plus /></el-icon>
          <template #tip>
            <div class="el-upload__tip">只能上传jpg/png文件，且不超过250kb</div>
          </template>
        </el-upload>
        <el-dialog v-model="dialogVisible">
          <img :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性" prop="spuSaleAttrList">
        <el-select
          :placeholder="
            filterBaseSaleAttrList.length
              ? `还有${filterBaseSaleAttrList.length}个未选择`
              : '没有数据了'
          "
          v-model="selectorBaseSaleAttr"
        >
          <el-option
            v-for="baseSaleAttr in filterBaseSaleAttrList"
            :key="baseSaleAttr.id"
            :label="baseSaleAttr.name"
            :value="`${baseSaleAttr.id}:${baseSaleAttr.name}`"
          />
        </el-select>
        <el-button
          type="primary"
          :icon="Plus"
          @click="addSaleAttr"
          :disabled="!selectorBaseSaleAttr"
          >添加销售属性</el-button
        >
        <el-table
          :data="spuFormData.spuSaleAttrList"
          style="width: 100%"
          border
        >
          <el-table-column
            type="index"
            label="序号"
            width="60"
            align="center"
          />
          <el-table-column prop="saleAttrName" label="属性名" width="150" />
          <el-table-column label="属性值名称列表">
            <template v-slot="{ row }">
              <el-tag
                v-for="(saleAttrValue, index) in row.spuSaleAttrValueList"
                :key="saleAttrValue.saleAttrValueName"
                class="mr-20"
                closable
                @close="delSaleAttrValue(row.spuSaleAttrValueList, index)"
              >
                {{ saleAttrValue.saleAttrValueName }}
              </el-tag>
              <el-input
                v-if="row.isEdit"
                size="small"
                class="spu-input"
                ref="inputRef"
                v-model="saleAttrValueName"
                @blur="switchShow(row)"
              />
              <el-button
                :icon="Plus"
                size="small"
                v-else
                @click="switchEdit(row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template v-slot="$index">
              <el-button
                type="danger"
                :icon="Delete"
                size="small"
                @click="delSelector($index)"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item class="mt-10">
        <el-button type="primary" @click="addOrUpdateSpu">保存</el-button>
        <el-button @click="showSpuList">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "AddOrUpdateSpu",
};
</script>

<script lang="ts" setup>
import { Plus, Delete } from "@element-plus/icons-vue";
import { reactive, ref, onMounted, computed, nextTick } from "vue";

import {
  baseSaleAttrListApi,
  saveSpuApi,
  getSpuImageListApi,
  getSpuSaleAttrListApi,
  updateSpuApi,
} from "@/api/product/spu";
import { getAllTrademarkListApi } from "@/api/product/trademark";

import type { TrademarkListModel } from "@/api/product/model/trademarkModel";
import type {
  BaseSaleAttrList,
  SpuFormData,
  SpuSaleAttrItem,
  SpuSaleAttrList,
  SpuSaleAttrValueList,
} from "@/api/product/model/spuModel";
import type { FormInstance, FormRules, UploadProps } from "element-plus";
import { useCategoryStore } from "@/stores/category";
import { useSpuStore } from "@/stores/spu";

import { ElMessage } from "element-plus";

const categoryStore = useCategoryStore();

const selectorBaseSaleAttr = ref("");

//销售属性功能
const filterBaseSaleAttrList = computed(() => {
  /*
baseSaleAttrList  指的是(还有xxx未选择) 销售属性列表  [id:xxx,name:xxx]
spuFormDate.spuSaleAttrValueList  指的是点击 添加销售属性  里面的(表格)  销售属性列表
[{baseSaleAttrId:xx , saleAttrName:xx ,spuSaleAttrValueList: [] }]
        baseSaleAttrId其实就来自于基础销售属性的id
        saleAttrName其实就来自于基础销售属性的name
    判断 基础销售属性列表Id 和 添加销售属性  里面的  销售属性列表的Id 是否相等 返回true
    表示 baseSaleAttrList(基础销售属性) 在 添加销售属性 里面的(表格)  销售属性列表  ，把他过滤掉  return false
    如果不在 添加销售属性 里面的(表格)  销售属性列表  就保留  return true

*/
  return baseSaleAttrList.value.filter((baseSaleAttr) => {
    return !spuFormData.spuSaleAttrList.some(
      (spuSaleAttr) => spuSaleAttr.baseSaleAttrId === baseSaleAttr.id
    );
  });
});

// 删除销售属性

const delSelector = (index: number) => {
  spuFormData.spuSaleAttrList.splice(index, 1);
};

// 点击添加销售属性
// baseSaleAttrId: +id  为字符串类型  字符串类型 与 number 类型比较有问题，所以讲类型转为number
const addSaleAttr = () => {
  const [id, name] = selectorBaseSaleAttr.value.split(":");

  spuFormData.spuSaleAttrList.push({
    baseSaleAttrId: +id,
    saleAttrName: name,
    spuSaleAttrValueList: [],
    isEdit: false,
  });

  // 把下拉框中选中的值清空
  selectorBaseSaleAttr.value = "";
};

const saleAttrValueName = ref("");

//点击切换编辑模式
const switchEdit = async (row: SpuSaleAttrItem) => {
  row.isEdit = true;
  await nextTick();
  inputRef.value.focus();
};

//点击切换显示模式

const switchShow = (row: SpuSaleAttrItem) => {
  if (saleAttrValueName.value) {
    row.spuSaleAttrValueList.push({
      baseSaleAttrId: row.baseSaleAttrId,
      saleAttrValueName: saleAttrValueName.value,
    });

    saleAttrValueName.value = "";
  }
  row.isEdit = false;
};

const inputRef = ref();

//点击删除属性
const delSaleAttrValue = (
  spuSaleAttrValueList: SpuSaleAttrValueList,
  index: number
) => {
  spuSaleAttrValueList.splice(index, 1);
};

//添加或更新

const addOrUpdateSpu = async () => {
  await spuFormRef.value?.validate();
  const id = spuFormStore.id;
  // await saveSpuApi
  const data = {
    ...spuFormData,
    tmId: spuFormData.tmId as number,
    spuImageList: spuFormData.spuImageList.map((img) => {
      return {
        imgName: img.name,
        imgUrl: img.response
          ? (img.response as { data: string }).data
          : (img.url as string),
      };
    }),
    category3Id: categoryStore.category3Id as number,
  };

  if (id) {
    updateSpuApi({
      ...data,
      id,
    });
  } else {
    await saveSpuApi(data);
  }

  ElMessage.success(`${id ? "修改" : "添加"}spu成功`);

  showSpuList();
};

// 上传图片功能
const BASE_URL = import.meta.env.VITE_API_URL;

// 所有品牌数据
const allTrademarkList = ref<TrademarkListModel>([]);

// 销售属性
const baseSaleAttrList = ref<BaseSaleAttrList>([]);

//上传图片成功
const handleAvatarSuccess = () => {
  if (spuFormData.spuImageList.length === 1) {
    spuFormRef.value?.clearValidate(["spuImageList"]);
  }
};

// 一挂载就要获取品牌和销售属性数据
onMounted(async () => {
  allTrademarkList.value = await getAllTrademarkListApi();
});
onMounted(async () => {
  baseSaleAttrList.value = await baseSaleAttrListApi();
});

onMounted(async () => {
  const id = spuFormStore.id;

  if (id) {
    //发送请求或请求图片数据得到数据：[{imgName:xxx,imgUrl:xxx}]
    //上传图片组件需要的数据：[{name:xxx,url:xxx}]

    const spuImageList = await getSpuImageListApi(id);
    spuFormData.spuImageList = spuImageList.map((img) => {
      return {
        name: img.imgName,
        url: img.imgUrl,
      };
    });
  }
});
onMounted(async () => {
  const id = spuFormStore.id;
  if (id) {
    spuFormData.spuSaleAttrList = await getSpuSaleAttrListApi(id);
  }
});
` `;
// 获取Form表单实例对象
const spuFormRef = ref<FormInstance>();

const spuFormStore = useSpuStore();

// 表单数据
const spuFormData = reactive<SpuFormData>({
  spuName: spuFormStore.spuName,
  tmId: spuFormStore.tmId,
  description: spuFormStore.description,
  spuImageList: [
    // {
    //   id: 0,
    //   imgName: "string",
    //   imgUrl: "string",
    //   spuId: 0,
    // },
  ],
  spuSaleAttrList: [
    // {
    //   baseSaleAttrId: 0,
    //   id: 0,
    //   saleAttrName: "string",
    //   spuId: 0,
    //   spuSaleAttrValueList: [
    //     {
    //       baseSaleAttrId: 0,
    //       id: 0,
    //       isChecked: "string",
    //       saleAttrName: "string",
    //       saleAttrValueName: "string",
    //       spuId: 0,
    //     },
    //   ],
    // },
  ],
});

/*
callback 是一个函数
      callback() 不传参数，就是校验通过
      callback(new Error('xxx')) 传参数，就是校验失败
        传递的参数就是失败的原因，就是错误提示信息
*/
const spuSaleAttrListValidator = (
  rule: any,
  value: SpuSaleAttrList,
  callback: any
) => {
  if (!value.length) {
    callback(new Error("请至少添加一个销售属性"));
    return;
  }

  if (!value.every((saleAttr) => saleAttr.spuSaleAttrValueList.length)) {
    callback(new Error("每个销售属性至少添加一个销售属性值"));
    return;
  }
  // if (value.some((saleAttr) => !saleAttr.spuSaleAttrValueList.length)) {
  //   callback(new Error("每个销售属性至少添加一个属性值"));
  //   return;
  // }

  //必须要调用
  callback();
};

// 表单校验
const spuFormRules = reactive<FormRules>({
  spuName: [{ required: true, message: "请输入SPU名称", trigger: "blur" }],
  tmId: [{ required: true, message: "请输入品牌名称", trigger: "change" }],
  description: [{ required: true, message: "请输入SPU描述", trigger: "blur" }],
  spuImageList: [{ required: true, message: "请上传SPU图片" }],
  spuSaleAttrList: [
    { required: true, validator: spuSaleAttrListValidator, trigger: "blur" },
  ],
});

const dialogImageUrl = ref("");
const dialogVisible = ref(false);

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url as string;
  dialogVisible.value = true;
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  // rawFile.type 文件类型

  const validImageType = ["image/jpeg", "image/jpg", "image/png"];
  if (!validImageType.includes(rawFile.type)) {
    ElMessage.error("图片类型只能是jpeg、jpg或png格式!");
    return false;
  } else if (rawFile.size / 1024 > 200) {
    ElMessage.error("图片大小必须小于200KB!");
    return false;
  }
  return true;
};

const MAX_UPLOAD_NUM = 3;
// 是否显示上传按钮

const isShowUploadBtn = computed(() => {
  return spuFormData.spuImageList.length < MAX_UPLOAD_NUM
    ? "inline-flex"
    : "none";
});

const emit = defineEmits(["setIsShow"]);

const showSpuList = () => {
  emit("setIsShow", 1);
};
</script>

<style scoped>
.spu-upload :deep(.el-upload) {
  display: v-bind(isShowUploadBtn);
}

.spu-input {
  width: 100px;
}
</style>
